<?php
namespace app\controllers;

use app\models\TagModel;

/**
 * 文章标签接口
 *
 * @param [type] $params
 * @return void
 */ 
class ApitagController extends ApiController
{
    /**
     * 文章列表
     *
     * @return json 
     */
    public function list() {
        $limit = 10;
        $offset = 0;
        if (isset($_GET['limit'])) {
            $limit = $_GET['limit'];
            $offset = isset($_GET['offset']) ? $_GET['offset']*$limit : 0;
        }
        $TagModel = new TagModel();
        $posts = $TagModel->findTags($limit, $offset);
        $data = [];
        foreach ($posts as $key=>$post) {
            $tData = [];
            $tData['value'] = $post['name'];
            $tData['id'] = $post['id'];
            array_push($data, $tData);
        }
        $result = [
            'code' => 0,
            'message' => 'suc',
            'data' => $data
        ];
        return $this->json($result);
    }

    public function info() {
        $result = ['code'=>1, 'message'=>''];
        if (!isset($_GET['id'])) {
            $result['message'] = '参数缺失';
            $this->json($result);
        }

        $id = $_GET['id'];
        $TagModel = new TagModel();
        $post = $TagModel->findPost($id);
        $result['code'] = 0;
        $result['message'] = '请求成功';
        $result['data'] = $post;
        $this->json($result);
    }

    public function add() {
        $result = ['code'=>1, 'message'=>''];
        if (!isset($_GET['name'])) {
            $result['message'] = '参数缺失';
            return $this->json($result);
        }

        $name = $_GET['name'];
        $TagModel = new TagModel();
        try {
            $iRe = $TagModel->addTag($name);
            $result['code'] = 0;
            $result['message'] = '添加标签成功';
            $result['data'] = $iRe;
        } catch (\Exception $e) {
            $result['message'] = $e->getMessage();
        }
        return $this->json($result);
    }
}